package cn.doctor.assistant.pad.db;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.lidroid.xutils.util.IOUtils;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DBBase {
	private boolean allowTransaction = true;
	private Lock writeLock = new ReentrantLock();
	private volatile boolean writeLocked = false;
	protected SQLiteDatabase database;
	// 数据库的Table是否存在
	private boolean checkedDatabase;

    public boolean isCheckedDatabase() {
        return checkedDatabase;
    }

    public void setCheckedDatabase(boolean checkedDatabase) {
        this.checkedDatabase = checkedDatabase;
    }
	
	public void beginTransaction() {
		if (allowTransaction) {
			database.beginTransaction();
		} else {
			writeLock.lock();
			writeLocked = true;
		}
	}

	public void setTransactionSuccessful() {
		if (allowTransaction) {
			database.setTransactionSuccessful();
		}
	}

	public void endTransaction() {
		if (allowTransaction) {
			database.endTransaction();
		}
		if (writeLocked) {
			writeLock.unlock();
			writeLocked = false;
		}
	}
	
	
	public synchronized boolean tableIsExist(SQLiteDatabase database, String tableName){
		if(checkedDatabase) return true;
		Cursor cursor = database.rawQuery("SELECT COUNT(*) AS c FROM sqlite_master WHERE type='table' AND name='" + tableName + "'", null);
        if (cursor != null) {
            try {
                if (cursor.moveToNext()) {
                    int count = cursor.getInt(0);
                    if (count > 0) {
                        setCheckedDatabase(true);
                        return true;
                    }
                }
            } catch (Throwable e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(cursor);
            }
        }

        return false;
	}

}
